<?php

class Core_Controller_Admincp_Storage_Edit extends Nuo_Controller_Admincp
{

	protected $_form = 'storage/admincp/local';

	function execute($request)
	{
		Nuo::setVar('breadcrum', array(
			'title' => 'Storage System',
			'toolbar' => 'admincp/core/storage',
		));
	
		$typeId = $request -> getParam('type_id');

		$storageId = $request -> getParam('storage_id');

		$table = Nuo::getTabLe('core/storage');

		$item = NULL;

		if ($storageId)
		{
			$item = $table -> find($storageId) -> current();
		}
		
		if($item)
		{
			$typeId  = $item->type_id;	
		}
		
		$type = Nuo::getTable('core/storage/type') -> find($typeId) -> current();
		
		$class = 'core/form/admincp/storage/'. $typeId;
		
		$form = Nuo::getObject($class);
		
		if ('GET' == $request -> getMethod() && $item)
		{
			$data = json_decode($item -> extra,1);
			$data  = array_merge($data, $item->toArray());
			$form -> setData($data);
		}

		if ('POST' == $request -> getMethod() && $form -> isValid($_POST))
		{
			$data = $form -> getData();

			$extra =  $data;
			
			unset($extra['is_storable']);
			unset($extra['is_default']);
			unset($extra['_footer']);

			$data['extra'] = json_encode($extra);
			$data['type_id'] = $typeId;

			if (NULL == $item)
			{
				$item = $table -> fetchNew();

			}

			$item -> fromArray($data);
			
			$item -> save();
			
			Nuo::getApi('core/storage')->cleanCache($item->getId());
			
			//Nuo::redirect('admincp/core/storage');
		}

		return  Nuo::getView()->render('core/view/controller/admincp/edit', $data = array('form' => $form));
	}

}
